package com.example.demo.service.impl;

import com.example.demo.service.MyProcessService;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.engine.ProcessEngine;
import org.flowable.engine.ProcessEngineConfiguration;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.repository.DeploymentQuery;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.repository.ProcessDefinitionQuery;
import org.flowable.image.ProcessDiagramGenerator;
import org.flowable.image.impl.DefaultProcessDiagramGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.List;

/**
 * @Author: njz
 * @Description:
 * @Date: create in 2022/2/11 11:26
 */
@Service
public class MyProcessServiceImpl implements MyProcessService {

    @Autowired
    private RepositoryService repositoryService;

    @Qualifier("processEngine")
    @Autowired
    private ProcessEngine processEngine;

    Logger logger= LoggerFactory.getLogger(MyProcessServiceImpl.class);


    /**
     * 查 act_re_procdef 表 id
     * @param proicessDefinitionId
     * @param response
     */
    //TODO 中文乱码
    @Override
    public void getProcessView(String proicessDefinitionId, HttpServletResponse response) throws UnsupportedEncodingException {
        BpmnModel bpmnModel = repositoryService.getBpmnModel(proicessDefinitionId);
        ProcessEngineConfiguration processEngineConfiguration=processEngine.getProcessEngineConfiguration();
        ProcessDiagramGenerator processDiagramGenerator=new DefaultProcessDiagramGenerator();
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("1.png", "UTF-8"));
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/octet-stream");
        try(
                InputStream in=processDiagramGenerator.generateDiagram(bpmnModel,"png", Collections.EMPTY_LIST, Collections.EMPTY_LIST,
                        processEngineConfiguration.getActivityFontName(), processEngineConfiguration.getLabelFontName(),
                        processEngineConfiguration.getAnnotationFontName(), processEngineConfiguration.getClassLoader(),
                        1.0,true);
                OutputStream out=response.getOutputStream();
        ){
            byte[] buffer=new byte[2048];
            int length;
            while( (length = in.read(buffer)) != -1){
                out.write(buffer,0,length);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 获取已部署的流程列表
     * @return
     */
    @Override
    public List<Deployment> getDeploymentList(Integer page, Integer size) {
        DeploymentQuery deploymentQuery = repositoryService.createDeploymentQuery();
        List<Deployment> deployments = deploymentQuery.listPage(page, size);
        return deployments;
    }

    @Override
    public Deployment getDeployment(String id) {
        DeploymentQuery deploymentQuery = repositoryService.createDeploymentQuery();
        return deploymentQuery.deploymentId(id).singleResult();
    }

    @Override
    public ProcessDefinition getProcessByDeploymentId(String deploymentId) {
        ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery();
        ProcessDefinition processDefinition = processDefinitionQuery.deploymentId(deploymentId).singleResult();
        return processDefinition;
    }

    @Override
    public List<ProcessDefinition> getProcessList(String deploymentId) {
        List<ProcessDefinition> processDefinitionList = repositoryService
                .createProcessDefinitionQuery()
                .deploymentId(deploymentId)
                .listPage(0,10);
        for(ProcessDefinition processDefinition: processDefinitionList){
            logger.info("流程定义为:{},版本为:{}",processDefinition.getName(),processDefinition.getVersion());
        }
        return processDefinitionList;
    }

    @Override
    public void suspendProcessDefinitionById(String id) {
        repositoryService.suspendProcessDefinitionById(id);
    }

    @Override
    public void activateProcessDefinitionById(String id) {
        repositoryService.activateProcessDefinitionById(id);
    }
}
